package org.quadraspace.resource;

import java.net.URI;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quadraspace.model.Mote;
import org.quadraspace.model.MoteIdentifier;
import org.quadraspace.service.MoteRepository;

@Path("/motes")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_XML)
public class MotesResource {
	private static final Log logger = LogFactory.getLog(MotesResource.class);
	private MoteRepository repository;

	public void setRepository(MoteRepository repostory) {
		this.repository = repostory;
	}

	@GET
	public List<Mote> getAllRegisteredMotes() {
		List<Mote> toRet = repository.getAllMotes();
		logger.debug("returning "+toRet.size()+" motes");
		return toRet;
	}

	@POST
	public Response registerMote(Mote s) {
		if (s.getId() == null) {
			String newId = repository.generateIdFor(s);
			logger.debug("generating id for mote: "+newId);
			s.setId(newId);
		} else {
			Mote exists = repository.getMoteWithID(s.getId());
			if (exists != null) {
				//return Bad Request
				logger.debug("mote with id "+s.getId()+" already present!");
				return Response.status(400).build();
			}
		}
		repository.registerMote(s);
		URI widgetId = UriBuilder.fromResource(MoteResource.class).build(s.getId());
		Response toRet = Response.created(widgetId).entity(new MoteIdentifier(s)).build();
		logger.debug("created new mote with id "+s.getId());
		return toRet;
	}
}
